import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    StatusBar,
    SectionList,
} from 'react-native';
import SideBar from "../normal/mySideBar";
import DataUtil from "../../util/DataUtil";

const ITEM_HEIGHT = 40; //item的高度
const HEADER_HEIGHT = 30;  //分组头部的高度
const SEPARATOR_HEIGHT = 0; //分割线的高度

/**
 * 抽取的选择城市列表
 * 属性:
 *
 * 必填项:
 * comp: 点击条目要跳转的目标Component
 * isSchool: 是否为学校列表 , 决定数据结构的处理方式以及跳转方式
 * data: 返回的json数据
 * nav: 主调函数的导航
 *
 * 选填项:
 * nameId: 调用者的js名 , 涉及到多级的id传值
    * provinceId 省id
    * cityId 市id
    * countyId 县id
 *
    * schoolId 学校Id
    * schoolName 学校名
    * log: 控制主界面显示
 */
export default class ChooseList extends Component {

    render() {
        return (
            <View style={{flex: 1}}>
                <SectionList
                    ref='list'
                    enableEmptySections
                    sections={
                        this.props.isSchool ? this._solveSchoolData(this.props.data) : this._solveData(this.props.data)
                    }
                    renderItem={({item}) =>
                        <View style={styles.itemView}
                        >
                            <Text style={{marginLeft: 5, fontSize: 16, color: '#333'}}
                                  onPress={() => {
                                      var nextRoute = {
                                          component: this.props.comp,
                                          passProps: {
                                              provinceId: this.props.nameId == 'province' ? item.key : this.props.provinceId,
                                              cityId: this.props.nameId == 'city' ? item.key : this.props.cityId,
                                              countyId: this.props.nameId == 'county' ? item.key : this.props.countyId,

                                              schoolId:item.key,
                                              schoolName:item.name,
                                              log:2,
                                          },
                                      };
                                      (this.props.nav).push(nextRoute);
                                  }}
                            >
                                {item.name}
                            </Text>
                        </View>}
                    renderSectionHeader={({section}) =>
                        <View style={[styles.headerView, {justifyContent: 'center', backgroundColor: "#eceeef"}]}>
                            <Text style={styles.headerText}>{section.title}</Text>
                        </View>
                    }
                    ItemSeparatorComponent={() => <View
                        style={{height: 1, width: 500, backgroundColor: '#F8FAFB'}}></View>}
                    getItemLayout={this._getItemLayout}
                />
                <SideBar
                    sections={
                        this.props.isSchool ? this.getSchoolFirstAll(this.props.data) : this.getFirstAll(this.props.data)
                    }
                    onSectionSelect={this._onSectionselect}
                />
                <View style={{backgroundColor: '#fff', height: 1}}></View>
            </View>
        );
    }

    _getItemLayout(data, index) {
        let [length, separator, header] = [ITEM_HEIGHT, SEPARATOR_HEIGHT, HEADER_HEIGHT];
        return {length, offset: (length + separator) * index + header, index};
    };

    _onSectionselect = (section, index) => {
        //跳转到某一项
        // this.refs.list.scrollToIndex({animated: true, index: this.state.sectionSize[index]})
        this.refs.list.scrollToLocation({
            animated: true,
            sectionIndex: index - 2,
            itemIndex: 0,
            viewPosition: 0,
            viewOffset: 0
        })
    };

    /**
     * 获取接收数据的首字母
     * @param data 数据源
     * @returns {Array} 排序过后的字母
     */
    getFirstAll(data) {
        //首先封装出现过的首字母
        let firstAll = [];
        let jsonData = data.list;
        for (let i = 0; i < jsonData.length; i++) {
            let first = jsonData[i].first;
            if (!DataUtil.contains(firstAll, first)) {
                //第一次出现的字母, 添加到集合中并生成新的item项
                firstAll[firstAll.length] = first;
            }
        }
        firstAll.sort();
        return firstAll;
    }

    getSchoolFirstAll(data) {
        //首先封装出现过的首字母
        let firstAll = [];
        let jsonData = data.list;
        for (let i = 0; i < jsonData.length; i++) {
            let first = (jsonData[i].simpleName)[0];
            if (!DataUtil.contains(firstAll, first)) {
                //第一次出现的字母, 添加到集合中并生成新的item项
                firstAll[firstAll.length] = first;
            }
        }
        firstAll.sort();
        return firstAll;
    }

    /**
     * 吧json数据转化为sections的对象数据并封装学校列表
     * @param responseData
     *
     [
     {title: 'D', data: [{name:'Devin',id=0}]},
     {title: 'J', data: [{name:'Jackson',id=0},{name:'James',id=0}] },
     ]
     *
     */
    _solveSchoolData(responseData) {
        console.log(JSON.stringify(responseData));
        let jsonData = responseData.list; //JSON数据
        let finalData = []; //最终数组对象
        let firstAll = []; //首字母集合

        //首先封装出现过的首字母
        for (let i = 0; i < jsonData.length; i++) {
            let first = (jsonData[i].simpleName)[0];
            if (!DataUtil.contains(firstAll, first)) {
                //第一次出现的字母, 添加到集合中并生成新的item项
                firstAll[firstAll.length] = first;
            }
        }
        firstAll.sort();

        //根据首字母进行对象的封装
        for (let j = 0; j < firstAll.length; j++) {
            let item = {}; //定义单个条目
            item.title = firstAll[j]; //条目的标题

            let item_obj = [];//条目中data的数组
            for (let z = 0; z < jsonData.length; z++) {
                if (firstAll[j] == (jsonData[z].simpleName)[0]) {
                    let inner = {};
                    inner.name = jsonData[z].name;
                    inner.key = jsonData[z].id;
                    item_obj[item_obj.length] = inner;
                }
            }
            item.data = item_obj; //条目数据
            item.keys = j;  //条目key
            finalData[j] = item
        }
        console.log(finalData);
        return finalData;
    }

    /**
     * 吧json数据转化为sections的对象数据
     * @param responseData
     *
     [
     {title: 'D', data: [{name:'Devin',id=0}]},
     {title: 'J', data: [{name:'Jackson',id=0},{name:'James',id=0}] },
     ]
     *
     */
    _solveData(responseData) {
        console.log(JSON.stringify(responseData));
        let jsonData = responseData.list; //JSON数据
        let finalData = []; //最终数组对象
        let firstAll = []; //首字母集合

        //首先封装出现过的首字母
        for (let i = 0; i < jsonData.length; i++) {
            let first = jsonData[i].first;
            if (!DataUtil.contains(firstAll, first)) {
                //第一次出现的字母, 添加到集合中并生成新的item项
                firstAll[firstAll.length] = first;
            }
        }
        firstAll.sort();

        //根据首字母进行对象的封装
        for (let j = 0; j < firstAll.length; j++) {
            let item = {}; //定义单个条目
            item.title = firstAll[j]; //条目的标题

            let item_obj = [];//条目中data的数组
            for (let z = 0; z < jsonData.length; z++) {
                if (firstAll[j] == jsonData[z].first) {
                    let inner = {}
                    inner.name = jsonData[z].name;
                    inner.key = jsonData[z].id;
                    item_obj[item_obj.length] = inner;
                }
            }
            item.data = item_obj; //条目数据
            item.keys = j;  //条目key
            finalData[j] = item
        }
        console.log(finalData);
        // finalData[finalData.length]="*";
        return finalData;
    }
}
var styles = StyleSheet.create({

    headerView: {
        justifyContent: 'center',
        height: HEADER_HEIGHT,
        paddingLeft: 20,
        backgroundColor: '#eee'
    },
    headerText: {
        fontSize: 15,
        // fontWeight: 'bold',
        // color: '#3cb775'
    },
    itemView: {
        justifyContent: 'center',
        backgroundColor: "#fff",
        flexDirection: 'column',
        padding: 12,
        alignItems: 'flex-start',
        height: ITEM_HEIGHT
    },
});


